package com.koron.css2.contractmanage.impl;

import cn.hutool.core.convert.NumberChineseFormatter;
import cn.hutool.core.util.ObjectUtil;
import com.koron.css2.ApplicationConfig;
import com.koron.css2.ServerInterface;
import com.koron.css2.baseConfig.bean.MeterBoreBean;
import com.koron.css2.baseConfig.mapper.BaseReceiptAccessoryMapper;
import com.koron.css2.baseConfig.mapper.ConfigMapper;
import com.koron.css2.baseConfig.mapper.MeterBoreMapper;
import com.koron.css2.clientCenter.bean.CtmInfoBean;
import com.koron.css2.clientCenter.bean.UserBean;
import com.koron.css2.clientCenter.mapper.CtmInfoMapper;
import com.koron.css2.clientCenter.mapper.UserInfoMapper;
import com.koron.css2.contractmanage.Enum.ContractStatusEnum;
import com.koron.css2.contractmanage.Enum.ContractTypeEnum;
import com.koron.css2.contractmanage.bean.ContractManageAddBean;
import com.koron.css2.contractmanage.bean.ContractManageBean;
import com.koron.css2.contractmanage.bean.PubCompanyContractBean;
import com.koron.css2.contractmanage.ecBean.EcContractConfigBean;
import com.koron.css2.contractmanage.exception.ContractException;
import com.koron.css2.contractmanage.mapper.ContractConfigMapper;
import com.koron.css2.contractmanage.mapper.ContractManageMapper;
import com.koron.css2.contractmanage.mapper.PubCompanyContractMapper;
import com.koron.css2.contractmanage.util.EcConstant;
import com.koron.css2.newProjectCenter.bean.PjCollection;
import com.koron.css2.newProjectCenter.bean.PjInfoBean;
import com.koron.css2.newProjectCenter.bean.PjMeter;
import com.koron.css2.newProjectCenter.bean.query.PjMeterQuery;
import com.koron.css2.newProjectCenter.mapper.PjCollectionMapper;
import com.koron.css2.newProjectCenter.mapper.PjInfoMapper;
import com.koron.css2.newProjectCenter.mapper.PjMeterMapper;
import com.koron.css2.serviceManage.bean.RequestBean;
import com.koron.css2.serviceManage.bean.UserInfoBean;
import com.koron.css2.serviceManage.utils.JsonUtils;
import com.koron.util.Constant;
import com.koron.util.Tools;
import net.qiyuesuo.v3sdk.SdkClient;
import net.qiyuesuo.v3sdk.model.common.DetailContract;
import net.qiyuesuo.v3sdk.model.common.Signatory;
import net.qiyuesuo.v3sdk.model.common.SimpleDocumentParam;
import net.qiyuesuo.v3sdk.model.contract.request.ContractCreatebycategoryRequest;
import net.qiyuesuo.v3sdk.model.contract.request.ContractDetailRequest;
import net.qiyuesuo.v3sdk.utils.SdkResponse;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.koron.ebs.mybatis.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.swan.bean.MessageBean;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

@Component
public class NewContractManageAdd implements ServerInterface {

    private static Logger logger = LoggerFactory.getLogger(NewContractManageAdd.class);

    private static final String SERVER_URL = ApplicationConfig.privateEcUrl;
    private static final String ACCESS_KEY = ApplicationConfig.privateEcToken;
    private static final String ACCESS_SECRET = ApplicationConfig.privateEcSecret;

    private static final String COMPANY = "COMPANY";
    private static final String PERSONAL = "PERSONAL";

    /**
     * 供水合同附件编号
     */
    private static String WATER_ACCESSORY_NO = "223";

    /**
     * 施工合同附件编号
     */
    private static String SG_ACCESSORY_NO = "222";

    /**
     * 供水合同
     */
    private static final String[] WATER_CONTRACT = {ContractTypeEnum.CONTRACT_TYPE_2.getContractType(), ContractTypeEnum.CONTRACT_TYPE_3.getContractType()};

    /**
     * 施工合同
     */
    private static final String[] SG_CONTRACT = {ContractTypeEnum.CONTRACT_TYPE_4.getContractType(), ContractTypeEnum.CONTRACT_TYPE_5.getContractType()};

    @Override
    public MessageBean<?> exec(SessionFactory factory, UserInfoBean userInfo, RequestBean req) {
        try {
            ContractManageAddBean contractManageAddBean = JsonUtils.objectToPojoIgnoreNone(req.getData(), ContractManageAddBean.class);
            ContractManageMapper contractManageMapper = factory.getMapper(ContractManageMapper.class);
            ConfigMapper configMapper = factory.getMapper(ConfigMapper.class);
            PubCompanyContractMapper pubCompanyContractMapper = factory.getMapper(PubCompanyContractMapper.class, "_default");
            UserInfoMapper userInfoMapper = factory.getMapper(UserInfoMapper.class);
            BaseReceiptAccessoryMapper baseReceiptAccessoryMapper = factory.getMapper(BaseReceiptAccessoryMapper.class);
             
            String ecCompanyName = configMapper.getConfigValueByNameOn(EcConstant.EC_COMPANY_NAME);
            String ecConstructionCompanyName = configMapper.getConfigValueByNameOn(EcConstant.EC_CONSTRUCTION_COMPANY_NAME);
            String contractType = contractManageAddBean.getContractType();
            Objects.requireNonNull(contractType, "合同类型不能为空");
            if(StringUtils.equalsAny(contractType, ContractTypeEnum.CONTRACT_TYPE_2.getContractType(), ContractTypeEnum.CONTRACT_TYPE_4.getContractType())) {
                //return MessageBean.create(Constant.MESSAGE_INT_FAIL, "合同模板不能为空", String.class);
            }
            List<String> contractIds = new ArrayList<>();
            List<String> errBuilder=new ArrayList<>();
            MessageBean msgBean = MessageBean.create(Constant.MESSAGE_INT_SUCCESS, "新增合同成功！", List.class);

            List<ContractManageBean> contractManageBeanList = contractManageAddBean.getContractManageBeanList();
            checkContractManageQuery(factory, contractManageBeanList, userInfo);

            StringBuilder failMsg = new StringBuilder("");
            if (StringUtils.isNotBlank(contractManageAddBean.getEcCategoryId()) && StringUtils.equalsAny(contractType, ContractTypeEnum.CONTRACT_TYPE_2.getContractType(), ContractTypeEnum.CONTRACT_TYPE_4.getContractType())) {//电子合同

                ContractConfigMapper contractConfigMapper = factory.getMapper(ContractConfigMapper.class);
                EcContractConfigBean config = contractConfigMapper.selectOneByEcCategoryId(contractManageAddBean.getEcCategoryId());
                Objects.requireNonNull(config, "业务ID不存在");
                // 轮询调签章平台接口
                for (ContractManageBean contractManageBean : contractManageBeanList) {
                    String userNo = contractManageBean.getUserNo();
                    // 先调签章平台创建电子合同接口，成功后合同表插入数据
                    try {
                        String contractNo;
                        do {
                            contractNo = Tools.getBillNo(factory, "EC_CONTRACT", userInfo.getCurWaterCode());
                        } while (contractManageMapper.countContractNo(contractNo) > 0);

                        UserBean tempUser = userInfoMapper.getUserInfoByUserNo(contractManageBean.getUserNo(), UserBean.USERTEMP);
                        // UserInfoVO userInfoVO = contractManageMapper.getUserInfoByUserNo(userNo);
                        if (tempUser == null || StringUtils.isEmpty(tempUser.getUserNo())) {
                            throw new ContractException("根据户号[" + userNo + "]找到的用户信息为空！");
                        }


                        contractManageBean.setContractNo(contractNo);
                        // 合同基本参数
                        ContractCreatebycategoryRequest contractRequest = new ContractCreatebycategoryRequest();
                        List<SimpleDocumentParam> SimpleparamMap= new ArrayList<>();
                        if (ContractTypeEnum.CONTRACT_TYPE_4.getContractType().equals(contractType)){
                            ecCompanyName=ecConstructionCompanyName;
                        }
                        setSignatorysAndCommonParam(factory, contractRequest, config, contractManageBean, ecCompanyName, SimpleparamMap);

                        // 初始化sdkClient
                        SdkClient sdkClient = new SdkClient(SERVER_URL, ACCESS_KEY, ACCESS_SECRET);

                        logger.debug("contractRequest：" + JsonUtils.objectToJson(contractRequest));

                        SdkResponse<String> response = sdkClient.service(contractRequest, String.class);

                        if (EcConstant.MESSAGE_SUCCESS == response.getCode()) {
                            String result = response.getResult();
                            Long contractId = Long.valueOf(result);
                            logger.info(userNo + "创建电子合同成功，合同ID:{}", contractId);
                            ContractDetailRequest request = new ContractDetailRequest();
                            request.setContractId(contractId);
                            SdkResponse<DetailContract> contractDetailResponse = sdkClient.service(request, DetailContract.class);
                            if (Constant.MESSAGE_INT_SUCCESS != contractDetailResponse.getCode()) {
                                logger.error("用户" + userNo + "查询合同[" + contractId + "]详情失败，response ==>：" + JsonUtils.objectToJson(contractDetailResponse));
                                throw new ContractException("查询合同[" + contractId + "]详情失败。");
                            }

                            contractManageBean.setCreateInfo(userInfo);
                            contractManageBean.setUpdateInfo(userInfo);

                            contractManageBean.setContractType(contractType);
                            contractManageBean.setContractStatus(ContractStatusEnum.CONTRACT_STATUS_1.getContractStatus());
                            contractManageBean.setRecordId(String.valueOf(contractId));
                            contractManageBean.setFileId(contractDetailResponse.getResult().getDocuments().get(0).getId());
                            contractManageBean.setContractName(config.getContractName());
                            contractIds.add(contractManageBean.getId());


                            // 插进合同表
                            int insertContractResult = contractManageMapper.insertContract(contractManageBean);
                            // 如果当前用户有纸质合同，并且是签约完成、归档完成的状态，更改纸质合同状态为已作废
                            // int updateContractResult = contractManageMapper.cancelPaperContractByContracType(userNo,contractType);
                            // 更改用户表信息
                            if (ContractTypeEnum.CONTRACT_TYPE_2.getContractType().equals(contractType)) {

                                int updateUserInfoResult = contractManageMapper.updateCtmUserInfo(contractManageBean);
                                int updateUserInfonew = contractManageMapper.updateUserInfo(contractManageBean);
                            }


                            // 插进水司公共库
                            PubCompanyContractBean pubBean = new PubCompanyContractBean();
                            pubBean.setGroupCode(userInfo.getCurWaterCode());
                            pubBean.setUserNo(userNo);
                            pubBean.setContractNo(contractNo);
                            pubBean.setProjectId(contractManageBean.getProjectId());
                            pubBean.setRecordId(String.valueOf(contractId));
                            pubBean.setCreateInfo(userInfo);
                            pubBean.setUpdateInfo(userInfo);
                            int insertPubResult = pubCompanyContractMapper.insertCompanyContract(pubBean);
                        } else {
                            failMsg.append("用户").append(userNo).append("新增电子合同失败：").append(response.getCode())
                                    .append("，").append(response.getMessage()).append("<br/>");
                            logger.error(failMsg.toString());
                            logger.error(response.toString());
                            errBuilder.add(contractManageBean.getUserNo()+"调用契约锁平台创建电子合同失败："+response.getMessage());
                            if (ContractTypeEnum.CONTRACT_TYPE_4.getContractType().equals(contractType)){
                                break;
                            }
                            continue;

                        }
                    } catch (Exception e) {
                        logger.error("用户" + userNo + "创建合同失败: " + e.getMessage(), e);
                        throw new RuntimeException("创建合同失败");
                    }
                    // 修改附件绑定的单据ID为合同信息的主键ID
                    if (StringUtils.isNotEmpty(contractManageBean.getTempId())){
                        baseReceiptAccessoryMapper.updateAccessoryReceiptId(contractManageBean.getId(), contractManageBean.getTempId());
                    }
                    if (ContractTypeEnum.CONTRACT_TYPE_4.getContractType().equals(contractType)) break;
                }

            } else {//纸质合同
                for (ContractManageBean contractManageBean : contractManageBeanList) {
                    try {
                        String userNo = contractManageBean.getUserNo();
                        String contractNo;
                        do {
                            contractNo = Tools.getBillNo(factory, "EC_CONTRACT", userInfo.getCurWaterCode());
                        } while (contractManageMapper.countContractNo(contractNo) > 0);

                        UserBean tempUser = userInfoMapper.getUserInfoByUserNo(contractManageBean.getUserNo(), UserBean.USERTEMP);
                        if (tempUser == null || StringUtils.isEmpty(tempUser.getUserNo())) {
                            throw new ContractException("根据户号[" + userNo + "]找到的用户信息为空！");
                        }

                       if (StringUtils.isBlank(contractManageBean.getContractNo())){
                           contractManageBean.setContractNo(contractNo);
                       }
                        contractManageBean.setCreateInfo(userInfo);
                        contractManageBean.setUpdateInfo(userInfo);
                        contractManageBean.setContractType(contractType);
                        contractManageBean.setContractStatus(ContractStatusEnum.CONTRACT_STATUS_2.getContractStatus());

                        // 插进合同表

                        int insertContractResult = contractManageMapper.insertContract(contractManageBean);
                        // 更改用户表信息
                        if (ContractTypeEnum.CONTRACT_TYPE_3.getContractType().equals(contractType)) {

                            int updateUserInfoResult = contractManageMapper.updateCtmUserInfo(contractManageBean);
                            int updateUserInfonew = contractManageMapper.updateUserInfo(contractManageBean);
                        }
                        //
                        contractIds.add(contractManageBean.getId());
                        // 修改附件绑定的单据ID为合同信息的主键ID
                        if (StringUtils.isNotEmpty(contractManageBean.getTempId())){

                            baseReceiptAccessoryMapper.updateAccessoryReceiptId(contractManageBean.getId(), contractManageBean.getTempId());
                        }
                        if (ContractTypeEnum.CONTRACT_TYPE_5.getContractType().equals(contractType)) break;


                    } catch (Exception e) {
                        logger.error(contractManageBean.getProjectId() + "普通合同创建失败", e);
                        MessageBean messageBean = MessageBean.create(Constant.MESSAGE_INT_FAIL, contractManageBean.getUserNo() + "普通合同创建失败！", String.class);
                        messageBean.setData(failMsg.toString());
                        return messageBean;
                    }
                }

            }
            // 假如是施工合同
            if (Arrays.asList(SG_CONTRACT).contains(contractType)){
                PjInfoMapper pjInfoMapper = factory.getMapper(PjInfoMapper.class);
                if (contractManageAddBean.getContractManageBeanList().size() > 0){
                    ContractManageBean contractManage = contractManageAddBean.getContractManageBeanList().get(0);
                    // 将施工合同编号填充到工程报装主表
                    pjInfoMapper.updateContractNo(contractManage.getProjectId(), contractManage.getContractNo());
                }
            }  
            if (ObjectUtil.isNotEmpty(errBuilder)){
                MessageBean<List> messageBean = MessageBean.create(Constant.MESSAGE_INT_FAIL, "合同创建失败: " + errBuilder, List.class);
                messageBean.setData(errBuilder);
                return messageBean;
            }
            msgBean.setData(contractIds);
            return msgBean;

        } catch (Exception e) {
            logger.error("合同创建失败: " + e.getMessage(), e);

            return MessageBean.create(Constant.MESSAGE_INT_FAIL, "合同创建失败: " + e.getMessage(), null);
        }


    }

    private void setSignatorysAndCommonParam(SessionFactory factory, ContractCreatebycategoryRequest contractRequest, EcContractConfigBean config, ContractManageBean contractManageBean, String ecCompanyName,  List<SimpleDocumentParam> SimpleparamMap) {
        try {
            UserInfoMapper userInfoMapper = factory.getMapper(UserInfoMapper.class);
            UserBean tempUser = userInfoMapper.getUserInfoByUserNo(contractManageBean.getUserNo(), UserBean.USERTEMP);
            Objects.requireNonNull(tempUser, "用户不存在");
            CtmInfoMapper ctmInfoMapper = factory.getMapper(CtmInfoMapper.class);
            CtmInfoBean tempCtm = ctmInfoMapper.getCtmInfoByCtmNo(tempUser.getCtmNo(), CtmInfoBean.CTMTEMP);
            PjMeterMapper pjMeterMapper = factory.getMapper(PjMeterMapper.class);
            MeterBoreMapper meterBoreMapper = factory.getMapper(MeterBoreMapper.class);
            PjInfoMapper pjInfoMapper = factory.getMapper(PjInfoMapper.class);
            PjInfoBean pjInfoBean = pjInfoMapper.selectByBillNo(contractManageBean.getBillNo());
            Objects.requireNonNull(pjInfoBean, "工程不存在");
            PjCollectionMapper pjCollectionMapper = factory.getMapper(PjCollectionMapper.class);

            PjCollection pjCollection = pjCollectionMapper.getSingleByPjId(pjInfoBean.getId());
            if (ContractTypeEnum.CONTRACT_TYPE_4.getContractType().equals(config.getContractType())) {
                contractManageBean.setMobile(tempCtm.getMobile());
            }

            String certType = contractManageBean.getCertType();

            String tenantType = config.getReceiverType();


            contractRequest.setSubject(config.getContractName() + "（" + contractManageBean.getName() + "）");
            contractRequest.setCategoryId(config.getEcCategoryId());
            contractRequest.setTenantName(ecCompanyName);
            contractRequest.setSend(true);
            // 第一行，接收方
            Signatory signatory1 = new Signatory();
            signatory1.setTenantName(contractManageBean.getName());
            signatory1.setTenantType(tenantType);
            signatory1.setReceiverName(contractManageBean.getName());
            signatory1.setContact(contractManageBean.getMobile());


            // 第二行，发起方
            Signatory signatory2 = new Signatory();
            signatory2.setTenantName(ecCompanyName);
            signatory2.setTenantType(COMPANY);

            // 设置签署方
            List<Signatory> signatories = new ArrayList<>();
            signatories.add(signatory1);
            signatories.add(signatory2);
            contractRequest.setSignatories(signatories);
//            DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy年MM月dd日");
//            String format = LocalDate.now().format(df);
            //签署日期
            Map<String, String> paramMap = new HashMap<>();
            paramMap.put("qdrq", LocalDate.now().toString());
            // 乙方名称
            paramMap.put("name", tempUser.getCtmName());
            // 客户地址
            paramMap.put("ctmAddr", tempUser.getCtmAddr());
            // 身份证号或统一社会信用代码
            paramMap.put("certNo", tempCtm.getCertNo());
            // 客户信息-手机号码
            paramMap.put("mobile", tempCtm.getMobile());
            //客户信息-客户地址
            paramMap.put("yfysdz", tempCtm.getCtmAddr());
            //用水类型
            paramMap.put("yfysxz", tempUser.getUseWaterTypeName());
            //水表口径
            paramMap.put("bjDN", "/");
            paramMap.put("bzsbkj", "/");

            if (StringUtils.isNotBlank(contractManageBean.getPjMeterId())) {
                String pjMeterId = contractManageBean.getPjMeterId();
                PjMeterQuery pjMeterQuery = new PjMeterQuery();
                pjMeterQuery.setId(pjMeterId);
                PjMeter pjMeter = pjMeterMapper.getSingle(pjMeterQuery);
                Objects.requireNonNull(pjMeter, "水表信息不存在");


                MeterBoreBean boreBean = meterBoreMapper.selectMeterBoreById(pjMeter.getMeterBore());

                paramMap.put("bjDN", boreBean == null ? pjMeter.getMeterBore() : String.valueOf(boreBean.getBoreValue()));
                MeterBoreBean boreBean2 = meterBoreMapper.selectMeterBoreById(pjInfoBean.getMeterBore());
                paramMap.put("bzsbkj", boreBean == null ? pjInfoBean.getMeterBore() : boreBean2.getBoreName());
            }


           // paramMap.put("userNo", tempUser.getUserNo());
            // 合同编号
            paramMap.put("contractNo", contractManageBean.getContractNo());
            // 户号
            paramMap.put("userNo", contractManageBean.getUserNo());
            //通知人手机
            paramMap.put("lxdh", tempUser.getMobile());
            //工程名称
            paramMap.put("gcmc", pjInfoBean.getPjName());
            //工程地址
            paramMap.put("gcdz", pjInfoBean.getInstallAddr());
            //收款金额
            paramMap.put("gcjed", "/");
            //工程报装-缴费日期
            paramMap.put("bzjkri", "/");
            paramMap.put("gcjex", "/");
            if (ObjectUtil.isNotNull(pjCollection)) {
                paramMap.put("gcje", pjCollection.getMoney().toString());
                if (StringUtils.isNotBlank(pjCollection.getPaymentDate())){
                    DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                    String format = LocalDateTime.parse(pjCollection.getPaymentDate(),fmt).toLocalDate().toString();
                    paramMap.put("bzjkri", format);
                }
                paramMap.put("gcjex", String.valueOf(pjCollection.getMoney()));
                //大写金额
                paramMap.put("gcjed", NumberChineseFormatter.format(pjCollection.getMoney().doubleValue(), true, true));
            }
            //报装水表个数
            paramMap.put("bzsbsl", pjInfoBean.getMeterNum().toString());


            for (String key : paramMap.keySet()) {
                paramMap.putIfAbsent(key, "/");
            }
            Iterator<Map.Entry<String, String>> iterator = paramMap.entrySet().iterator();
            while (iterator.hasNext()) {
                SimpleDocumentParam documentParam = new SimpleDocumentParam();
                Map.Entry<String, String> entry = iterator.next();
                documentParam.setName(entry.getKey());
                documentParam.setValue(entry.getValue());
                SimpleparamMap.add(documentParam);
            }
            contractRequest.setDocumentParams(SimpleparamMap);
        } catch (Exception e) {
            logger.error("设置签署方和通用模板字段错误",e);
            throw new RuntimeException("设置签署方和通用模板字段错误");
        }

    }


    /**
     * 校验合同字段
     *
     * @param contractManageBeanList
     * @param factory
     * @param userInfo
     * @return
     */
    public void checkContractManageQuery(SessionFactory factory, List<ContractManageBean> contractManageBeanList, UserInfoBean userInfo) {
        if (CollectionUtils.isEmpty(contractManageBeanList)) {
            throw new ContractException("合同增加请求参数不能为空！");
        }
        ContractManageMapper contractManageMapper = factory.getMapper(ContractManageMapper.class);
        BaseReceiptAccessoryMapper baseReceiptAccessoryMapper = factory.getMapper(BaseReceiptAccessoryMapper.class);
        PjMeterMapper pjMeterMapper = factory.getMapper(PjMeterMapper.class);

        /**
         * 校验是否存在重复的合同编号
         */
        Set<String> contractNoSet = contractManageBeanList.stream().map(t -> t.getContractNo()).collect(Collectors.toSet());
        if (contractNoSet.size() != contractManageBeanList.size()){
            throw new ContractException("存在重复的合同编号");
        }
        /**
         * 校验是否存在重复的用户编号
         */
        Set<String> userNoSet = contractManageBeanList.stream().map(t -> t.getUserNo()).collect(Collectors.toSet());
        if (userNoSet.size() != contractManageBeanList.size()){
            throw new ContractException("存在重复的用户编号");
        }
        for (int i = 0; i < contractManageBeanList.size(); i ++) {
            ContractManageBean contractManageBean = contractManageBeanList.get(i);
            String userNo = contractManageBean.getUserNo();
            String contractType = contractManageBean.getContractType();
            String contractNo = contractManageBean.getContractNo();
            String projectId = contractManageBean.getProjectId();
            String billNo = contractManageBean.getBillNo();
            // 假如是 供水合同并且户号为空
            if (Arrays.asList(WATER_CONTRACT).contains(contractManageBean.getContractType()) && StringUtils.isBlank(userNo)) {
                throw new ContractException("参数中的户号不能为空！");
            }
            if (StringUtils.isBlank(projectId)) {
                throw new ContractException("参数中的报装单ID不能为空！");
            }
            if (StringUtils.isBlank(billNo)) {
                throw new ContractException("参数中的报装单编号不能为空！");
            }
            //假如合同类型是普通供水合同
            if (Objects.equals(contractManageBean.getContractType(), ContractTypeEnum.CONTRACT_TYPE_3.getContractType())){
                PjMeterQuery query = new PjMeterQuery();
                query.setId(contractManageBean.getPjMeterId());
                PjMeter pjMeter = pjMeterMapper.getSingle(query);
                // 供水合同是否存在附件
                int count = baseReceiptAccessoryMapper.countByReceiptId(contractManageBean.getTempId(), WATER_ACCESSORY_NO);
                if (count == 0){
                    throw new ContractException("第" + (i + 1)+ "行必须上传供水合同附件");
                }
            }
            // 假如合同类型是施工合同
            if (Objects.equals(contractManageBean.getContractType(), ContractTypeEnum.CONTRACT_TYPE_5.getContractType())){
                // 施工合同是否存在附件
                int count = baseReceiptAccessoryMapper.countByReceiptId(contractManageBean.getTempId(), SG_ACCESSORY_NO);
                if (count == 0){
                    throw new ContractException("必须上传施工合同附件");
                }
            }

            // 普通供水合同
            if (ContractTypeEnum.CONTRACT_TYPE_3.getContractType().equals(contractType) && StringUtils.isBlank(contractNo) || ContractTypeEnum.CONTRACT_TYPE_5.getContractType().equals(contractType) && StringUtils.isBlank(contractNo)) {
                throw new ContractException("第" + (i + 1)+ "行合同编号不能为空！");
            }

            // 普通合同
            if (ContractTypeEnum.CONTRACT_TYPE_3.getContractType().equals(contractType)) {
                // 查询该供水合同编号系统中是否已存在
                int countContractNo = contractManageMapper.countContractNo(contractNo);
                if (countContractNo > 0) {
                    throw new ContractException("第" + (i + 1)+ "行：合同编号[" + contractNo + "]系统中已存在");
                }
                String[] contractTypes = new String[]{ContractTypeEnum.CONTRACT_TYPE_2.getContractType(),ContractTypeEnum.CONTRACT_TYPE_3.getContractType()};
                int countUserContractNo = contractManageMapper.countContractTypeEleContract(userNo, contractTypes, contractManageBean.getProjectId());
                if (countUserContractNo > 0) {
                    throw new ContractException("第" + (i + 1)+ "行,该用户有签署中或已签署的合同，暂时无法签订");
                }
            }

            // 电子合同
            if (ContractTypeEnum.CONTRACT_TYPE_2.getContractType().equals(contractType)) {
                String[] contractTypes = new String[]{ContractTypeEnum.CONTRACT_TYPE_2.getContractType(),ContractTypeEnum.CONTRACT_TYPE_3.getContractType()};
                int countUserContractNo = contractManageMapper.countContractTypeEleContract(userNo, contractTypes, contractManageBean.getProjectId());
                if (countUserContractNo > 0) {
                    throw new ContractException("第" + (i + 1)+ "行,用户[" + userNo + "]已签供水合同，如需重签请先作废旧合同！");
                }
            }

            // 电子施工合同
            if (ContractTypeEnum.CONTRACT_TYPE_4.getContractType().equals(contractType)) {
                String[] contractTypes = new String[]{ContractTypeEnum.CONTRACT_TYPE_4.getContractType(),ContractTypeEnum.CONTRACT_TYPE_5.getContractType()};
                int countContractNo = contractManageMapper.countContractTypeEleContract(null, contractTypes, contractManageBean.getProjectId());
                if (countContractNo > 0) {
                    throw new ContractException("存在签署中或已签署的合同，暂时无法签订");
                }
            }

            // 普通施工合同
            if (ContractTypeEnum.CONTRACT_TYPE_5.getContractType().equals(contractType)) {
                //查询该施工合同编号系统中是否已存在
                int countContractNo = contractManageMapper.countContractNo(contractNo);
                if (countContractNo > 0) {
                    throw new ContractException("系统中已存在该合同编号[" + contractNo + "],请重新输入");
                }
                String[] contractTypes = new String[]{ContractTypeEnum.CONTRACT_TYPE_5.getContractType(),ContractTypeEnum.CONTRACT_TYPE_4.getContractType()};
                int countUserContractNo = contractManageMapper.countContractTypeEleContract(null, contractTypes, contractManageBean.getProjectId());
                if (countUserContractNo > 0) {
                    throw new ContractException("存在签署中或已签署的合同，暂时无法签订");
                }
            }
        }
    }
}
